package com.yyx.qq.helpers;

import static com.yyx.qq.models.ClusterType.DIALOG_CONTAINER;
import static com.yyx.qq.models.ClusterType.NORMAL;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Message;
import android.widget.ExpandableListView;
import android.widget.ListAdapter;
import android.widget.Toast;

import com.yyx.qq.C;
import com.yyx.qq.QQMain;
import com.yyx.qq.R;
import com.yyx.qq.models.Cluster;
import com.yyx.qq.models.Dummy;
import com.yyx.qq.models.DummyType;
import com.yyx.qq.models.Group;
import com.yyx.qq.models.GroupType;
import com.yyx.qq.models.ModelRegistry;
import com.yyx.qq.models.Status;
import com.yyx.qq.models.User;
import com.yyx.qq.MyAdapter;

import edu.tsinghua.lumaqq.qq.beans.DownloadFriendEntry;
import edu.tsinghua.lumaqq.qq.beans.NormalIM;
import edu.tsinghua.lumaqq.qq.beans.NormalIMHeader;

public class UIHelper {
	private QQMain main;
	// QQ好友列表
	private List<List<Map<String, Object>>> childData;
	// 好友分组信息
	private List<Map<String, Object>> groupData;
	// 信息
	private String MsgResult;

	private static final String DISPLAY = "DISPLAY";
	private static final String NICK = "NICK";
	private static final String DISPLAYNAME = "DISPLAYNAME";
	private static final String FEMALE = "FEMALE";
	private static final String SIGNATURE = "SIGNATURE";

	// 群分组信息
	private List<Map<String, String>> groupClusterData;
	// 群QQ好友列表
	private List<List<Map<String, String>>> childClusterData;

	// 所有的缺省组和用户自定义组
	private Group latestGroup;
	private Group clusterGroup;
	private Group myFriendGroup;
	private Group strangerGroup;
	private Group blacklistGroup;
	private List<Group> normalGroups;

	private MyAdapter mAdapter;
	private ListAdapter listAdapter;

	private ExpandableListView lvGroup;
	private ExpandableListView lvCluster;

	private Bitmap female;
    private Bitmap male;
	
	public UIHelper(QQMain main) {
		this.main = main;
		childData = new ArrayList<List<Map<String, Object>>>();
		groupData = new ArrayList<Map<String, Object>>();

		childClusterData = new ArrayList<List<Map<String, String>>>();
		groupClusterData = new ArrayList<Map<String, String>>();

		normalGroups = new ArrayList<Group>();

		lvGroup = (ExpandableListView) main.findViewById(R.id.listGroup);
		lvCluster = (ExpandableListView) main.findViewById(R.id.listCluster);
		
		female = BitmapFactory.decodeResource(main.getResources(), R.drawable.female);
		male = BitmapFactory.decodeResource(main.getResources(), R.drawable.male);
	}

	public void appendMessage(User f, NormalIM im, NormalIMHeader header) {
		MsgResult = f.displayName + DateTool.format(header.sendTime) + ":";
		MsgResult += im.message;
		handler.sendEmptyMessage(C.id.MSG_INFO_ID);
	}

	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			switch (msg.what) {
			case C.id.MSG_GROUP_ID:
				mAdapter = new MyAdapter(main, 
						groupData,
						R.layout.list_item_1,
						new String[] { DISPLAY, NICK }, 
						new int[] {android.R.id.text1, android.R.id.text2 },
						childData,
						R.layout.new_friend_list,
						new String[] {NICK, SIGNATURE,FEMALE}, 
						new int[] {R.id.friend_nick,R.id.friend_signature,R.id.friend_female});
				lvGroup.setAdapter(mAdapter);
				break;
			case C.id.MSG_INFO_ID:
				Toast.makeText(main, MsgResult, Toast.LENGTH_LONG).show();
				break;
			case C.id.MSG_CLUSTER_ID:
				mAdapter = new MyAdapter(main,
						groupClusterData,
						android.R.layout.simple_expandable_list_item_1,
						new String[] { DISPLAY, NICK }, new int[] {
								android.R.id.text1, android.R.id.text2 },
						childClusterData,
						android.R.layout.simple_expandable_list_item_2,
						new String[] { DISPLAY, NICK }, new int[] {
								android.R.id.text1, android.R.id.text2 });
				lvCluster.setAdapter(mAdapter);
				break;
			}
			super.handleMessage(msg);

		}
	};
	

	public void setMessage(String messageResult) {
		MsgResult = messageResult;
		handler.sendEmptyMessage(C.id.MSG_INFO_ID);
	}

	/**
	 * 添加一个用户到某种组中。如果是添加到群组，则不操作。如果是自定义的 好友组，不操作。如果是最近联系人组，则添加一个link
	 * 
	 * @param user
	 *            User对象
	 * @param type
	 *            组类型
	 */
	public void addUser(User user, GroupType type) {
		User u = user;
		Group g = null;
		switch (type) {
		case BLACKLIST_GROUP:
			g = blacklistGroup;
			break;
		case DEFAULT_FRIEND_GROUP:
			g = myFriendGroup;
			break;
		case LATEST_GROUP:
			g = latestGroup;
			break;
		case STRANGER_GROUP:
			g = strangerGroup;
			break;
		case CLUSTER_GROUP:
		case FRIEND_GROUP:
			return;
		default:
			return;
		}
		g.addUser(u);
	}

	/**
	 * 刷新所有视图
	 */
	public void refreshAll() {
		resetMode();
	}

	/**
	 * 初始化model
	 */
	public void initModels() {
		ModelRegistry.clearAll();
		normalGroups.clear();

		latestGroup = new Group();
		latestGroup.name = "最近联系人";
		latestGroup.groupType = GroupType.LATEST_GROUP;

		clusterGroup = new Group();
		clusterGroup.name = "群";
		clusterGroup.groupType = GroupType.CLUSTER_GROUP;

		myFriendGroup = new Group();
		myFriendGroup.name = "我的好友";
		myFriendGroup.groupType = GroupType.DEFAULT_FRIEND_GROUP;

		strangerGroup = new Group();
		strangerGroup.name = "陌生人";
		strangerGroup.groupType = GroupType.STRANGER_GROUP;

		blacklistGroup = new Group();
		blacklistGroup.name = "黑名单";
		blacklistGroup.groupType = GroupType.BLACKLIST_GROUP;
	}

	/**
	 * 重设整个model,将数据清空，然后再加入
	 * 
	 * @param groupNames
	 *            组名列表，不包括我的好友组
	 * @param friends
	 *            所有下载项
	 */
	public void resetModel(List<String> groupNames,
			List<DownloadFriendEntry> friends) {
		// 清除旧的数据
		ModelRegistry.clearGroup(myFriendGroup, false);
		ModelRegistry.clearGroup(clusterGroup, false);
		for (Group g : normalGroups){
			ModelRegistry.clearGroup(g, true);
		}
		// 把旧的内容保存下来
		Map<Integer, User> oldUsers = new HashMap<Integer, User>();
		Map<Integer, Cluster> oldClusters = new HashMap<Integer, Cluster>();
		for (User u : myFriendGroup.users){
			oldUsers.put(u.qq, u);
		}
		//群
		int size = clusterGroup.clusters.size();
		for (int i = size - 1; i >= 0; i--) {
			Cluster c = clusterGroup.clusters.get(i);
			if (c.clusterType == DIALOG_CONTAINER)
				continue;
			c.removeAllSubClusters();
			oldClusters.put(c.clusterId, c);
		}
		for (Group g : normalGroups) {
			for (User u : g.users)
				oldUsers.put(u.qq, u);
			g.removeAllUsers();
		}
		normalGroups.clear();
		myFriendGroup.removeAllUsers();
		clusterGroup.removeAllCluster();

		// 创建新的组
		for (String name : groupNames) {
			Group g = new Group();
			g.name = name;
			g.expanded = false;
			normalGroups.add(g);
			ModelRegistry.addGroup(g);
		}

		// 添加新的组
		size = getUploadGroupCount();
		List<DownloadFriendEntry> needInfos = new ArrayList<DownloadFriendEntry>();
		for (DownloadFriendEntry entry : friends) {
			if (entry.isCluster()) {
				// 如果这个组存在，使用老对象，如果不存在，新建一个Cluster对象
				Cluster c = oldClusters.get(entry.qqNum);
				if (c == null) {
					needInfos.add(entry);
					c = new Cluster();
					c.clusterId = entry.qqNum;
					c.name = String.valueOf(entry.qqNum);
					c.headId = 1;
					c.clusterType = NORMAL;

					// 创建两个dummy，一个是群内组织，一个是讨论组
					Dummy orgDummy = new Dummy();
					orgDummy.dummyType = DummyType.CLUSTER_ORGANIZATION;
					orgDummy.name = "cluster_organization";
					c.addDummy(orgDummy);
					Dummy subDummy = new Dummy();
					subDummy.dummyType = DummyType.SUBJECTS;
					subDummy.name = "cluster_subject";
					c.addDummy(subDummy);
				}
				// 注册cluster
				clusterGroup.addCluster(c);
				ModelRegistry.addCluster(c);
			} else {
				if (entry.group >= size)
					entry.group = 0;

				User u = oldUsers.get(entry.qqNum);

				if (u == null) {
					needInfos.add(entry);
					u = new User();
					u.qq = entry.qqNum;
					u.nick = String.valueOf(u.qq);

				} else {
					u.status = Status.OFFLINE;
				}
				getFriendGroup(entry.group).addUser(u);
			}
		}

		resetMode();

		// 得到新的model的信息
		for (DownloadFriendEntry dfe : needInfos) {
			if (dfe.isCluster() && dfe.qqNum != 0) {
				main.getClient().cluster_GetInfo(dfe.qqNum);
				main.getClient().cluster_getSubjectList(dfe.qqNum);
			} else
				main.getClient().user_GetInfo(dfe.qqNum);
		}

		// 得到多人对话列表
		main.getClient().cluster_getDialogList();
	}

	/**
	 * 得到好友组，第0个好友组是我的好友组
	 * 
	 * @param index
	 *            好友组索引
	 * @return Group
	 */
	public Group getFriendGroup(int index) {
		if (index < 0)
			return null;
		if (index == 0)
			return myFriendGroup;
		return normalGroups.get(index - 1);
	}

	/**
	 * @return 需要上传的组数目
	 */
	public int getUploadGroupCount() {
		return normalGroups.size() + 1;
	}

	/**
	 * 重设显示模式
	 */
	private void resetMode() {
		groupData.clear();
		childData.clear();

		setGroupViewModel(myFriendGroup, groupData, childData);
		for (Group g : normalGroups) {
			setGroupViewModel(g, groupData, childData);
		}

		handler.sendEmptyMessage(C.id.MSG_GROUP_ID);

	}
	
	/**
	 * 设置组内数据
	 * @param g
	 * @param gd
	 * @param cd
	 */
	private void setGroupViewModel(Group g, List<Map<String, Object>> gd,
			List<List<Map<String, Object>>> cd) {
		if (g.getUserCount() > 0) {
			Map<String, Object> curGroupMap = new HashMap<String, Object>();
			gd.add(curGroupMap);
			curGroupMap.put(DISPLAY, g.name + "(" + g.getUserCount() + ")");
			curGroupMap.put(NICK, g.name);
			List<Map<String, Object>> children = new ArrayList<Map<String, Object>>();
			for (int i = 0; i < g.getUserCount(); i++) {
				Map<String, Object> curChildMap = new HashMap<String, Object>();
				User u = g.users.get(i);
				curChildMap.put(DISPLAY, Integer.toString(u.qq));
				curChildMap.put(NICK, u.nick);
				if(u.female){
					curChildMap.put(FEMALE, female);
				}else{
					curChildMap.put(FEMALE, male);
				}
				curChildMap.put(SIGNATURE, u.signature);
				//TODO 
				children.add(curChildMap);
			}
			cd.add(children);
		}
	}

	private void setClusterViewModel(Cluster c, List<Map<String, String>> gd,
			List<List<Map<String, String>>> cd) {
		Map<String, String> curGroupMap = new HashMap<String, String>();
		gd.add(curGroupMap);
		curGroupMap.put(DISPLAY, c.name);
		curGroupMap.put(NICK, Integer.toString(c.clusterId));
		List<Map<String, String>> children = new ArrayList<Map<String, String>>();
		for (User u : c.members.values()) {
			Map<String, String> curChildMap = new HashMap<String, String>();
			children.add(curChildMap);
			curChildMap.put(DISPLAY, Integer.toString(u.qq));
			curChildMap.put(NICK, u.nick);
		}
		cd.add(children);
	}

	/**
	 * 删除一个群的model，如果存在这个群的相关窗口，也将关闭他们
	 * 
	 * @param clusterId
	 *            群的内部ID
	 * @return 成功则返回true
	 */
	public boolean removeCluster(int clusterId) {
		// 找到群组
		Cluster c = ModelRegistry.removeCluster(clusterId);
		if (c == null || c.clusterType == DIALOG_CONTAINER)
			return false;

		// 删除群
		clusterGroup.removeCluster(c);
		if (c.clusterType != NORMAL) {
			Cluster parent = ModelRegistry.getCluster(c.parentClusterId);
			if (parent != null)
				parent.removeSubCluster(c);
		}
		// 返回true表示成功
		return true;
	}

	public void refreshGroup() {
		groupClusterData.clear();
		childClusterData.clear();
		for (Cluster c : clusterGroup.clusters) {
			setClusterViewModel(c, groupClusterData, childClusterData);
		}
		handler.sendEmptyMessage(C.id.MSG_CLUSTER_ID);
	}
}
